<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import { fromLonLat } from 'ol/proj'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { GeoJSON } from 'ol/format'
import { Fill, Icon, Stroke, Style, Text } from 'ol/style'  // 确保导入Text
import { Feature } from 'ol'
import Point from 'ol/geom/Point'
import { Select } from 'ol/interaction'

// 地图DOM引用和实例
const mapRef = ref(null)
const mapInstance = ref(null)

// 地图中心点和视图配置
const center = fromLonLat([113.267252, 23.137949])
const mapView = ref(new View({
  center: center,
  zoom: 10,
  projection: 'EPSG:3857'
}))

// 预定义样式
const defaultStyle = new Style({
  fill: new Fill({ color: 'rgba(0,0,0,0.4)' }),
  stroke: new Stroke({ color: 'red' })
})

const hoverStyle = new Style({
  fill: new Fill({ color: 'blue' })
})

// 图标样式（拆分为两个Style对象）
const createIconStyle = (label = '') => [
  new Style({
    image: new Icon({
      src: '/icon.png',
      scale: 0.2,
      anchor: [0.5, 1], // 图标底部中心为锚点
      onerror: () => console.error('图标加载失败')
    })
  }),
  new Style({
    text: new Text({
      text: label,
      font: 'bold 12px Microsoft YaHei', // 必须指定字体
      fill: new Fill({ color: '#333' }),
      offsetY: -25, // 文字向上偏移
      backgroundFill: new Fill({
        color: 'rgba(255,255,255,0.7)'
      }),
      padding: [3, 5],
      stroke: new Stroke({
        color: 'rgba(0,0,0,0.3)',
        width: 1
      })
    })
  })
]

// 高德地图底图
const tiandituLayer = new TileLayer({
  source: new XYZ({
    url: 'https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
    crossOrigin: 'anonymous'
  })
})

// 矢量边界层
const vectorLayer = new VectorLayer({
  source: new VectorSource({
    url: 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json',
    format: new GeoJSON()
  }),
  style: defaultStyle
})

// 图标层
const iconSource = new VectorSource()
const iconLayer = new VectorLayer({
  source: iconSource,
  zIndex: 2
})

// 初始化图标
const initIcon = () => {
  const iconFeature = new Feature({
    geometry: new Point(fromLonLat([114.25, 30.59])),
    label: '武汉' // 添加标签属性
  })
  iconFeature.setStyle(createIconStyle(iconFeature.get('label')))
  iconSource.addFeature(iconFeature)
}
const select = new Select(

)
// 地图初始化
onMounted(() => {
  nextTick(() => {
    mapInstance.value = new Map({
      target: mapRef.value,
      view: mapView.value,
      layers: [tiandituLayer, vectorLayer, iconLayer]
    })
    // 初始化图标
    initIcon()
    mapInstance.value.addInteraction(select)
    select.on('select',e => {
      console.log(e)
    })
    // 指针移动事件（悬停高亮）
    mapInstance.value.on('pointermove', (e) => {
      const features = vectorLayer.getSource().getFeaturesAtCoordinate(e.coordinate)
      vectorLayer.getSource().forEachFeature(f => f.setStyle(defaultStyle))
      if (features.length > 0) {
        features[0].setStyle(hoverStyle)
      }
    })

    // 点击添加图标
    mapInstance.value.on('click', (e) => {
      const iconFeature = new Feature({
        geometry: new Point(e.coordinate),
        label: '新标记' + (iconSource.getFeatures().length + 1) // 动态标签
      })
      iconFeature.setStyle(createIconStyle(iconFeature.get('label')))
      iconSource.addFeature(iconFeature)
    })

    // 确保地图尺寸正确
    mapInstance.value.updateSize()
  })
})

// 组件卸载时清理
onBeforeUnmount(() => {
  if (mapInstance.value) {
    mapInstance.value.setTarget(undefined)
    mapInstance.value = null
  }
})
</script>

<template>
  <div id="map-container">
    <div ref="mapRef" id="map"></div>
  </div>
</template>

<style scoped>
#map-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

#map {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style>
